import React, { useState, useEffect } from 'react';
import {
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  message,
  Dropdown,
  Avatar,
  Badge
} from 'antd';
import {
  PlusOutlined,
  SearchOutlined,
  EditOutlined,
  DeleteOutlined,
  KeyOutlined,
  MoreOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { MenuProps } from 'antd';
import dayjs from 'dayjs';
import * as userService from '@/services/user';
import type { 
  User, 
  UserQueryParams, 
  CreateUserRequest, 
  UpdateUserRequest,
  ApiPaginatedResponse
} from '@/types';
import SearchForm, { SearchFieldConfig } from '@/components/SearchForm';
import DataTable, { PaginationConfig, ToolbarAction, BatchAction } from '@/components/DataTable';

const { Option } = Select;

// 用户状态配置
const USER_STATUS = {
  active: { color: 'green', text: '正常' },
  inactive: { color: 'orange', text: '停用' },
  banned: { color: 'red', text: '封禁' },
  deleted: { color: 'gray', text: '已删除' }
};

// 用户角色配置
const USER_ROLES = {
  admin: { color: 'blue', text: '管理员' },
  user: { color: 'default', text: '普通用户' },
  merchant: { color: 'orange', text: '商户' }
};

const UserList: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState<User[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [pagination, setPagination] = useState<PaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 搜索表单
  const [searchForm] = Form.useForm();
  const [searchParams, setSearchParams] = useState<UserQueryParams>({});

  // 模态框状态
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [resetPasswordModalVisible, setResetPasswordModalVisible] = useState(false);
  const [currentUser, setCurrentUser] = useState<User | null>(null);

  // 表单
  const [createForm] = Form.useForm();
  const [editForm] = Form.useForm();
  const [resetPasswordForm] = Form.useForm();

  // 搜索字段配置
  const searchFields: SearchFieldConfig[] = [
    {
      name: 'keyword',
      type: 'input',
      placeholder: '用户名/邮箱/昵称',
      width: 200,
      prefix: <SearchOutlined />
    },
    {
      name: 'status',
      type: 'select',
      placeholder: '选择状态',
      width: 120,
      options: [
        { label: '正常', value: 'active' },
        { label: '停用', value: 'inactive' },
        { label: '封禁', value: 'banned' }
      ]
    },
    {
      name: 'role',
      type: 'select',
      placeholder: '选择角色',
      width: 120,
      options: [
        { label: '管理员', value: 'admin' },
        { label: '普通用户', value: 'user' },
        { label: '商户', value: 'merchant' }
      ]
    },
    {
      name: 'dateRange',
      type: 'dateRange',
      placeholder: '注册时间'
    }
  ];

  // 获取用户列表
  const fetchUsers = async (params: UserQueryParams = {}) => {
    setLoading(true);
    try {
      const queryParams = {
        page: pagination.current,
        limit: pagination.pageSize,
        ...searchParams,
        ...params,
      };

      const response: ApiPaginatedResponse<User> = await userService.getUserList(queryParams);
      if (response.success && response.data) {
        setUsers(response.data.items || []);
        setPagination(prev => ({
          ...prev,
          current: response.data.pagination?.page || 1,
          total: response.data.pagination?.total || 0,
        }));
      }
    } catch (error: any) {
      message.error(error?.message || '获取用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始化
  useEffect(() => {
    fetchUsers();
  }, []);

  // 搜索
  const handleSearch = () => {
    const values = searchForm.getFieldsValue();
    const params: UserQueryParams = {
      page: 1,
      limit: pagination.pageSize,
    };

    if (values.keyword) params.keyword = values.keyword;
    if (values.status) params.status = values.status;
    if (values.role) params.role = values.role;
    if (values.dateRange && values.dateRange.length === 2) {
      params.startDate = values.dateRange[0].format('YYYY-MM-DD');
      params.endDate = values.dateRange[1].format('YYYY-MM-DD');
    }

    setSearchParams(params);
    setPagination(prev => ({ ...prev, current: 1 }));
    fetchUsers(params);
  };

  // 重置搜索
  const handleResetSearch = () => {
    searchForm.resetFields();
    setSearchParams({});
    setPagination(prev => ({ ...prev, current: 1 }));
    fetchUsers({ page: 1, limit: pagination.pageSize });
  };

  // 分页变化
  const handlePaginationChange = (page: number, pageSize?: number) => {
    setPagination(prev => ({ ...prev, current: page, pageSize: pageSize || 10 }));
    fetchUsers({ ...searchParams, page, limit: pageSize || 10 });
  };

  // 创建用户
  const handleCreate = async () => {
    try {
      const values = await createForm.validateFields();
      await userService.createUser(values as CreateUserRequest);
      message.success('用户创建成功');
      setCreateModalVisible(false);
      createForm.resetFields();
      fetchUsers();
    } catch (error: any) {
      message.error(error?.message || '创建用户失败');
    }
  };

  // 编辑用户
  const handleEdit = (user: User) => {
    setCurrentUser(user);
    editForm.setFieldsValue(user);
    setEditModalVisible(true);
  };

  // 更新用户
  const handleUpdate = async () => {
    try {
      const values = await editForm.validateFields();
      if (currentUser) {
        await userService.updateUser(currentUser.id, values as UpdateUserRequest);
        message.success('用户信息更新成功');
        setEditModalVisible(false);
        setCurrentUser(null);
        editForm.resetFields();
        fetchUsers();
      }
    } catch (error: any) {
      message.error(error?.message || '更新用户失败');
    }
  };

  // 重置密码
  const handleResetPassword = (user: User) => {
    setCurrentUser(user);
    setResetPasswordModalVisible(true);
  };

  // 确认重置密码
  const handleConfirmResetPassword = async () => {
    try {
      const values = await resetPasswordForm.validateFields();
      if (currentUser) {
        await userService.resetUserPassword(currentUser.id, values);
        message.success('密码重置成功');
        setResetPasswordModalVisible(false);
        setCurrentUser(null);
        resetPasswordForm.resetFields();
      }
    } catch (error: any) {
      message.error(error?.message || '重置密码失败');
    }
  };

  // 删除用户
  const handleDelete = async (user: User) => {
    try {
      await userService.deleteUser(user.id);
      message.success('用户删除成功');
      fetchUsers();
    } catch (error: any) {
      message.error(error?.message || '删除用户失败');
    }
  };

  // 批量操作
  const handleBatchUpdateStatus = async (status: 'active' | 'inactive' | 'banned') => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要操作的用户');
      return;
    }

    try {
      const result = await userService.batchUpdateUserStatus({
        ids: selectedRowKeys as number[],
        status,
      });
      message.success(`批量更新状态成功，影响${result.updatedCount}个用户`);
      setSelectedRowKeys([]);
      fetchUsers();
    } catch (error: any) {
      message.error(error?.message || '批量更新状态失败');
    }
  };

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的用户');
      return;
    }

    try {
      const result = await userService.batchDeleteUsers(selectedRowKeys as number[]);
      message.success(`批量删除成功，影响${result.deletedCount}个用户`);
      setSelectedRowKeys([]);
      fetchUsers();
    } catch (error: any) {
      message.error(error?.message || '批量删除失败');
    }
  };

  // 表格列配置
  const columns: ColumnsType<User> = [
    {
      title: '用户信息',
      key: 'userInfo',
      width: 200,
      render: (_, record) => (
        <Space>
          <Avatar size="small" src={record.avatar}>
            {record.username.charAt(0).toUpperCase()}
          </Avatar>
          <div>
            <div className="font-medium">{record.username}</div>
            <div className="text-gray-500 text-sm">{record.email}</div>
          </div>
        </Space>
      ),
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname',
      render: (nickname) => nickname || '-',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      render: (phone) => phone || '-',
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: (role: 'admin' | 'user' | 'merchant') => (
        <Tag color={USER_ROLES[role]?.color}>
          {USER_ROLES[role]?.text}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: 'active' | 'inactive' | 'banned' | 'deleted') => (
        <Badge
          status={status === 'active' ? 'success' : status === 'inactive' ? 'warning' : 'error'}
          text={USER_STATUS[status]?.text}
        />
      ),
    },
    {
      title: '注册时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (date) => date ? dayjs(date).format('YYYY-MM-DD HH:mm') : '-',
    },
    {
      title: '最后登录',
      dataIndex: 'last_login_at',
      key: 'last_login_at',
      render: (date) => date ? dayjs(date).format('YYYY-MM-DD HH:mm') : '-',
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => {
        const items: MenuProps['items'] = [
          {
            key: 'edit',
            icon: <EditOutlined />,
            label: '编辑',
            onClick: () => handleEdit(record),
          },
          {
            key: 'resetPassword',
            icon: <KeyOutlined />,
            label: '重置密码',
            onClick: () => handleResetPassword(record),
          },
          {
            type: 'divider',
          },
          {
            key: 'delete',
            icon: <DeleteOutlined />,
            label: '删除',
            danger: true,
            onClick: () => {
              Modal.confirm({
                title: '确认删除',
                content: `确定要删除用户 "${record.username}" 吗？`,
                onOk: () => handleDelete(record),
              });
            },
          },
        ];

        return (
          <Dropdown menu={{ items }} placement="bottomRight">
            <Button type="text" icon={<MoreOutlined />} />
          </Dropdown>
        );
      },
    },
  ];

  // 工具栏动作配置
  const toolbarActions: ToolbarAction[] = [
    {
      key: 'create',
      label: '新建用户',
      type: 'primary',
      icon: <PlusOutlined />,
      onClick: () => setCreateModalVisible(true)
    }
  ];

  // 批量操作配置
  const batchActions: BatchAction[] = [
    {
      key: 'active',
      label: '设为正常',
      onClick: () => handleBatchUpdateStatus('active'),
    },
    {
      key: 'inactive',
      label: '设为停用',
      onClick: () => handleBatchUpdateStatus('inactive'),
    },
    {
      key: 'banned',
      label: '设为封禁',
      onClick: () => handleBatchUpdateStatus('banned'),
    },
    {
      key: 'delete',
      label: '批量删除',
      danger: true,
      onClick: () => {
        Modal.confirm({
          title: '确认批量删除',
          content: `确定要删除所选的 ${selectedRowKeys.length} 个用户吗？`,
          onOk: handleBatchDelete,
        });
      },
    },
  ];

  return (
    <div className="space-y-6">
      {/* 搜索区域 */}
      <SearchForm
        fields={searchFields}
        form={searchForm}
        onSearch={handleSearch}
        onReset={handleResetSearch}
        loading={loading}
      />

      {/* 用户列表 */}
      <DataTable<User>
        title="用户列表"
        columns={columns}
        dataSource={users}
        rowKey="id"
        loading={loading}
        pagination={{
          ...pagination,
          onChange: handlePaginationChange,
        }}
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
          getCheckboxProps: (record: User) => ({
            disabled: record.status === 'deleted',
          }),
        }}
        toolbarActions={toolbarActions}
        batchActions={batchActions}
        scroll={{ x: 1200 }}
      />

      {/* 创建用户模态框 */}
      <Modal
        title="创建用户"
        open={createModalVisible}
        onOk={handleCreate}
        onCancel={() => {
          setCreateModalVisible(false);
          createForm.resetFields();
        }}
        destroyOnClose
      >
        <Form form={createForm} layout="vertical">
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' },
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          <Form.Item
            name="password"
            label="密码"
            rules={[
              { required: true, message: '请输入密码' },
              { min: 6, message: '密码长度至少6位' },
            ]}
          >
            <Input.Password placeholder="请输入密码" />
          </Form.Item>
          <Form.Item name="nickname" label="昵称">
            <Input placeholder="请输入昵称" />
          </Form.Item>
          <Form.Item name="phone" label="手机号">
            <Input placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item name="role" label="角色" initialValue="user">
            <Select>
              <Option value="user">普通用户</Option>
              <Option value="admin">管理员</Option>
              <Option value="merchant">商户</Option>
            </Select>
          </Form.Item>
          <Form.Item name="status" label="状态" initialValue="active">
            <Select>
              <Option value="active">正常</Option>
              <Option value="inactive">停用</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑用户模态框 */}
      <Modal
        title="编辑用户"
        open={editModalVisible}
        onOk={handleUpdate}
        onCancel={() => {
          setEditModalVisible(false);
          setCurrentUser(null);
          editForm.resetFields();
        }}
        destroyOnClose
      >
        <Form form={editForm} layout="vertical">
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' },
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          <Form.Item name="nickname" label="昵称">
            <Input placeholder="请输入昵称" />
          </Form.Item>
          <Form.Item name="phone" label="手机号">
            <Input placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item name="role" label="角色">
            <Select>
              <Option value="user">普通用户</Option>
              <Option value="admin">管理员</Option>
              <Option value="merchant">商户</Option>
            </Select>
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select>
              <Option value="active">正常</Option>
              <Option value="inactive">停用</Option>
              <Option value="banned">封禁</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 重置密码模态框 */}
      <Modal
        title="重置密码"
        open={resetPasswordModalVisible}
        onOk={handleConfirmResetPassword}
        onCancel={() => {
          setResetPasswordModalVisible(false);
          setCurrentUser(null);
          resetPasswordForm.resetFields();
        }}
        destroyOnClose
      >
        <Form form={resetPasswordForm} layout="vertical">
          <Form.Item
            name="newPassword"
            label="新密码"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码长度至少6位' },
            ]}
          >
            <Input.Password placeholder="请输入新密码" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserList; 